﻿using System.Collections.Generic;
using SalaryReport.Core.Excel;

namespace SalaryReport.Core
{
    public class SalaryInfo
    {
        private const int EMAIL_INDEX = 1;

        public List<ExcelData> Items { get; private set; }

        public string Template { get; private set; }

        public SalaryInfo(List<ExcelData> items, string template)
        {
            Items = items;
            Template = template;
        }

        public string ParseTemplate()
        {
            foreach (var item in Items)
            {
                if (!string.IsNullOrEmpty(item.NameTemplate))
                {
                    Template = Template.Replace(item.NameTemplate, RoundExelValue(item.Value));
                }
            }

            return Template;
        }

        public string GetEmail()
        {
            return Items[EMAIL_INDEX].Value;
        }

        private string RoundExelValue(string value)
        {
            ulong num;
            var commaParts = value.Split(',');
            var dotParts = value.Split('.');
            
            if (commaParts.Length == 2)
            {
                if (commaParts[1].Length > 2 && ulong.TryParse(commaParts[1], out num))
                {
                    var fraction = commaParts[1].Remove(2);
                    return commaParts[0] + ',' + fraction;
                }
            }
            
            if (dotParts.Length == 2)
            {
                if (dotParts[1].Length > 2 && ulong.TryParse(dotParts[1], out num))
                {
                    var fraction = dotParts[1].Remove(2);
                    return dotParts[0] + '.' + fraction;
                }
            }

            return value;
        }
    }
}